<template>
  <div class="div">
    <PageTitle title="卡券列表"></PageTitle>
    <div>
      <div class="btn-wrapper">
        <el-button type="primary" size="mini" @click="dialogVisible = true">添加</el-button>
        <el-button type="primary" size="mini" @click="toggleSelection(tableData)">反选</el-button>
        <el-button type="primary" size="mini" @click="downLoadQR">生成二维码</el-button>
      </div>
    </div>
    <el-table
      stripe
      :data="tableData"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="code"
        label="编号">
      </el-table-column>
      <el-table-column
        prop="name"
        label="所属活动">
          <template>
            {{ activity_name }}
          </template>
      </el-table-column>
      <el-table-column
        label="兑换用户">
          <!-- <template slot-scope="scope">
            <el-button type="text" @click="showDetail(scope.row.id)">查看</el-button>
          </template> -->
          <template slot-scope="scope">
            <el-button type="text" @click="showUser(scope.row.promotion_id, scope.row.id)">查看</el-button>
          </template>
      </el-table-column>
    </el-table>
    <div class='pagination-wrapper'>
      <el-pagination
        layout="prev, pager, next, sizes"
        @current-change="pageChange"
        :page-size="pageSize"
        :total="totalCount"
        :current-page="pageNum"
        :page-sizes="pageSizeArr"
        @size-change="sizeChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="添加卡券"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="所属活动">
            <el-input v-model="activity_name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item v-if="many==2" label="数量" prop="num">
          <el-input v-model="ruleForm.num" placeholder="请输入数量"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="兑换用户"
      :visible.sync="userVisible"
      width="30%"
    >
      <div class="main">
        <h3>
          兑换用户：
          <strong>共{{count}}个</strong>
        </h3>
        <div class="item" v-for="(item,index) in user" :key="index">
          <span>用户：{{item.name}}</span>
          <span>领取时间：{{item.time}}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userVisible = false">取 消</el-button>
        <el-button type="primary" @click="userVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  import PageTitle from '@/components/pageTitle/PageTitle.vue'
  export default {
    name: 'CouponList',
    components: {
      PageTitle
    },
    activated() {
      this._getList()
    },
    deactivated() {
      this.$destroy()
    },
    data() {
      return {
        activity_name: this.$route.params.name,
        many:this.$route.params.many,
        url:null,
        tableData: [],
        pageNum: 1,
        totalCount: 0,
        pageSize: 10,
        dialogImageUrl: '',
        multipleSelection: [],
        dialogVisible: false,
        userVisible: false,
        pageSizeArr: [10, 20, 50, 100],
        ruleForm: {
          activity_id: '',
          num: ''
        },
        rules: {
          num: [
            { required: true, message: '请输入数量', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^[0-9][0-9]*$/).test(value)
                if (!boolean) {
                  return callback(new Error('请输入正整数'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
        },
        user: '',
        count:0,
      }
    },
    computed: {
      couponIdArr() {
        let arr = this.multipleSelection.map(item => {
          return item.id
        })
        return arr.toString()
      }
    },
    methods: {
      /*
      *查看详情
      */
      showDetail(e){
        console.log('详情e---------',e)
      },
      async _getList() {
        let { data: { code, data } } = await this.$axios({
          url: this.$api + '/v1/pcode/list',
          method: 'GET',
          params: {
            size: this.pageSize,
             page: this.pageNum,
            promotion_id: this.$route.params.id
          }
        })
        if(code == 0) {
          this.tableData = data.items
          this.totalCount = data.page.totalCount
        }
      },
      async _get(activityId, id) {
        let { data: { code, data } } = await this.$axios({
          url: this.$api + '/v1/pcode/details',
          method: 'GET',
          params: {
            promotion_id: activityId,
            id
          }
        })
        if (code == 0) {
          this.user = data.name.map(item=>{
            return {name:item}
          })
          this.user.forEach((item,index)=>{
            item.time = data.na[index]
          })
          this.count = data.count
          console.log('this.user------',this.user)
          this.userVisible = true
        }else{
          this.user = []
          this.count = 0
          this.userVisible = true
        }
      },
      // 提交表单
      submitForm(formName) {
        if(this.many==2){
            this.$refs[formName].validate(valid => {
                if (!valid) {
                    return false
                } else {
                    this.url = '/v1/pcode/pcode'
                    this._submit()
                }
            })
        }else{
            this.url = '/v1/pcode/random'
           this._submit() 
        }
      },
      _submit: _.throttle(async function() {
        let { data: { code, data } } = await this.$axios({
          url: this.$api + this.url,
          method: 'POST',
          data:{
            promotion_id: this.$route.params.id,
            num:this.ruleForm.num
          }
        })
        if(code == 0) {
          this.$message.success(data)
          setTimeout(() => {
            this.dialogVisible = false
            this._getList()
            this.ruleForm.num = ''
          }, 1500)
        }
      }, 2000, { trailing: false }),
      toggleSelection(rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      downLoadQR() {
        if (this.multipleSelection.length) {
          this._downLoadQR()
        }
      },
      _downLoadQR: _.throttle(function() {
        let token = localStorage.getItem('token')
        let time = new Date().getTime()
        location.href = 'http://admin.youjingxi.com.cn/v1/code/pdown?token=' + token + '&id=' + this.couponIdArr + '&time=' + time
      }, 2000, { trailing: false }),
      pageChange(pageNum) {
        this.pageNum = pageNum
        this._getList()
      },
      sizeChange(size) {
        this.pageNum = 1
        this.pageSize = size
        this._getList()
      },
      showUser(activityId, id) {
        this._get(activityId, id)
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/select-bar.scss';
  .list-img {
     width: 50px;
     cursor: pointer;
  }
  .el-button--text {
    text-decoration: none;
  }
  .btn-wrapper {
    margin-top: 10px;
  }
  .main span{
    margin: 15px 10px;
    display: inline-block;
  }
  .main .item{
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #f0f0f0;
  }
</style>